import React, { useState, useEffect, useRef } from "react";
import { findDOMNode } from "react-dom";
import { Input, Button, Form } from "antd";
import { EditOutlined } from "@ant-design/icons";

export interface FieldEditProps {
  /** 如果存在name，获得name和输入的值,返回一个对象--{password:123}，否则返回字符串--{value:123}  */
  successCallback?: (rst: Record<string, string>) => void;
  /** 默认显示的文字 */
  text?: string;
  /** 输入文字校验 */
  rules?: any[];
  name?: string;
  label?: string;
  width?: number;
  inputType?: "input" | "textarea";
  placeholder?: string;
}

/**
 * 单独编辑信息的输入组件
 */

export default (props: FieldEditProps) => {
  const inputRef = useRef(null);
  const {
    placeholder,
    label,
    successCallback,
    text = "",
    rules = [],
    name = "",
    width = 200,
    inputType = "input"
  } = props;

  const [isEdit, setIsEdit] = useState(false);
  const [inputText, setInputText] = useState("");

  useEffect(() => {
    setInputText(text);
  }, [text]);

  const handleClickOutside = (e: any) => {
    // 组件已挂载且事件触发对象不在div内
    const result = findDOMNode(inputRef.current).contains(e.target);
    if (!result) {
      setIsEdit(false);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", (e) => handleClickOutside(e), false);
    return document.removeEventListener(
      "mousedown",
      (e) => handleClickOutside(e),
      false
    );
  }, []);

  return (
    <div ref={inputRef} style={{ display: "inline-block" }}>
      <div style={{ display: isEdit === false ? "none" : "block" }}>
        <div style={{ display: "flex" }}>
          <Form.Item label={label} name={name} rules={rules}>
            {inputType !== "textarea" ? (
              <Input
                value={inputText}
                onChange={(e) => {
                  setInputText(e.target.value);
                }}
                style={{ width }}
                placeholder={placeholder}
              />
            ) : (
              <Input.TextArea
                rows={4}
                value={inputText}
                onChange={(e) => {
                  setInputText(e.target.value);
                }}
                style={{ width: 600 }}
                placeholder={placeholder}
              />
            )}
          </Form.Item>

          <div>
            <Button
              onClick={() => {
                const hasRequired = rules.find((f: any) => f.required);
                if (
                  hasRequired &&
                  hasRequired.required === true &&
                  inputText === ""
                ) {
                  return false;
                }

                const hasPattern = rules.find((f: any) => f.pattern);

                if (hasPattern && hasPattern.pattern) {
                  hasPattern.pattern.lastIndex = 0;
                  if (hasPattern.pattern.test(inputText) === false) {
                    return false;
                  }
                }
                setIsEdit(false);
                successCallback!(
                  name ? { [name]: inputText } : { value: inputText }
                );
              }}
              type="link"
            >
              确定
            </Button>
            <Button onClick={() => setIsEdit(false)} type="text">
              取消
            </Button>
          </div>
        </div>
      </div>
      <div
        style={{
          display: isEdit === true ? "none" : "block"
        }}
      >
        <div style={{ display: "flex", alignItems: "center" }}>
          <span
            style={{
              maxWidth: "400px",
              display: "inline-block",
              overflow: "hidden",
              textOverflow: "ellipsis"
            }}
          >
            {text}
          </span>
          <EditOutlined
            style={{ paddingLeft: 10 }}
            onClick={() => {
              setIsEdit(true);
            }}
          />
        </div>
      </div>
    </div>
  );
};
